package com.solt.prism.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.solt.prism.dao.imp.SqlConnectionPool;

public class CategoriesDao {

	private static CategoriesDao instance = null;
	private Map<Integer, Integer> mapCatSet;
	private Set<Integer> setCats ;
	public static String CAT_SQL = "SELECT id , section FROM jos_categories";
	public static String CAT_SQL_SERVER = "SELECT categoryID FROM Category";

	private CategoriesDao(boolean isSqlServer) {
		mapCatSet = new HashMap<Integer, Integer>();
		setCats = new HashSet<Integer>();
		if (!isSqlServer ) {
			loadDataFromMySql();
		} else {
			loadDataFromSqlServer ();
		}
		

	}
	
	
	public boolean isContain (int categoryId) {
		return setCats.contains(categoryId);
	}
	
	
	public  void loadDataFromSqlServer() {
		Statement st = null;
		ResultSet re = null;
		Connection con = null;
		try {
			
			con = SqlConnectionPool.getSqlServerConnection();
			st = con.createStatement();
			re = st.executeQuery(CAT_SQL_SERVER);

			while (re.next()) {
				int catId = re.getInt("CategoryID");
				setCats.add(catId);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			System.exit(-1);
		} finally {
			try {
				if (st != null)
					st.close();
				if (con != null)
					re.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
				System.exit(-1);
			}
			
		}
	}


	public static synchronized CategoriesDao getInstance (boolean isSqlServer) {
		if (instance == null) {
			instance = new CategoriesDao(isSqlServer);
		}
		return instance;
	}
	
	
	
	public Integer getSetionIdOfCatId(int catId) {
		return mapCatSet.get(catId);
	}

	private void loadDataFromMySql() {
		Statement st = null;
		ResultSet re = null;
		Connection con = null;
		try {
			
			con = SqlConnectionPool.getConnection();
			st = con.createStatement();
			re = st.executeQuery(CAT_SQL);

			while (re.next()) {
				int catId = re.getInt("id");
				int section = Integer.parseInt(re.getString("section"));
				mapCatSet.put(catId, section);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			System.exit(-1);
		} finally {
			try {
				if (st != null)
					st.close();
				if (con != null)
					re.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
				System.exit(-1);
			}
			
		}

		

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(CategoriesDao.getInstance(true).isContain(13));
	}

}
